<script setup>
import { ref, onMounted, computed } from "vue";
import LoginModal from "../components/LoginModal.vue";
import SettingModal from "../components/SettingModal.vue";
import StartQuestion from "../components/StartQuestion.vue";
import CompleteModal from "../components/CompleteModal.vue";
import RankingModal from "../components/RankingModal.vue";
import QuestionModal from "../components/QuestionModal.vue";
import api from "../api/index.js";
import avatar1Png from '@/assets/images/8/a1.png'
import avatar2Png from '@/assets/images/8/a2.png'
import avatar3Png from '@/assets/images/8/a3.png'
import avatar4Png from '@/assets/images/8/a4.png'
import avatar5Png from '@/assets/images/8/a5.png'
import avatar6Png from '@/assets/images/8/a6.png'
import avatar7Png from '@/assets/images/8/a7.png'
import avatar8Png from '@/assets/images/8/a8.png'
import avatar9Png from '@/assets/images/8/a9.png'
import avatar10Png from '@/assets/images/8/a10.png'

// 头像映射
const avatarMap = {
	1: avatar1Png,
	2: avatar2Png,
	3: avatar3Png,
	4: avatar4Png,
	5: avatar5Png,
	6: avatar6Png,
	7: avatar7Png,
	8: avatar8Png,
	9: avatar9Png,
	10: avatar10Png
}

// 弹窗状态管理
const modalStates = ref({
	login: false,
	setting: false,
	startQuestion: false,
	complete: false,
	ranking: false,
	question: false
});

const userNickname = ref(localStorage.getItem('userNickname') || '');
const userAvatar = ref(localStorage.getItem('userAvatar') || '');

// 统一的弹窗控制方法
const openModal = (modalName) => {
	modalStates.value[modalName] = true;
	if (modalName === 'question') {
		closeModal('startQuestion');
	}
};

const closeModal = (modalName) => {
	modalStates.value[modalName] = false;
};

const closeAllModals = () => {
	Object.keys(modalStates.value).forEach(key => {
		modalStates.value[key] = false;
	});
};

// 检查本地存储中是否有用户昵称
const checkUserNickname = () => {
	const storedNickname = localStorage.getItem('userNickname');
	if (storedNickname) {
		userNickname.value = storedNickname;
		return true;
	}
	return false;
};

// 测试 API 调用功能
const testApiCalls = async () => {
	try {
		api.auth.getToken().then(res => {
			console.log('获取到的 token:', res);
			if (res.access_token) {
				localStorage.setItem('token', res.access_token);
				localStorage.setItem('refresh_token', res.refresh_token);
			}
		});
	} catch (error) {
		console.error('API 测试失败:', error.message);
	}
};

// 处理开始按钮点击
const handleStartClick = () => {
	if (!checkUserNickname()) {
		// 如果没有昵称，显示登录弹窗
		openModal('login');
	} else {
		// 如果有昵称，直接开始答题
		openModal('question');
	}
};

// 处理登录成功
const handleLogin = (nickname) => {
	userNickname.value = nickname;
	// 登录成功后，保存用户昵称到本地存储
	localStorage.setItem('userNickname', nickname);
	// 随机一个头像， 1-10 随机一个数字
	const randomAvatar = Math.floor(Math.random() * 10) + 1;
	localStorage.setItem('userAvatar', randomAvatar.toString());
	userAvatar.value = randomAvatar.toString();

	// 登录成功后，关闭登录弹窗
	api.user.saveUserInfo({
		title: userNickname.value,
		paths: userAvatar.value
	}).then(res => {
		localStorage.setItem('userId', res.data.id);
	});
};

// 保存设置
const handleSaveSettings = (settings) => {
	console.log('接收到的设置数据:', settings);

	// 先更新本地变量
	userNickname.value = settings.nickname;
	userAvatar.value = settings.avatar.toString();

	// 保存到本地存储
	localStorage.setItem('userNickname', settings.nickname);
	localStorage.setItem('userAvatar', settings.avatar);

	//更新用户信息到后端
	let id = localStorage.getItem('userId');
	api.user.updateUserInfo({
		title: settings.nickname,  // 使用新的昵称
		paths: settings.avatar.toString(),  // 使用新的头像
		id
	}).then(res => {
		console.log('用户信息更新成功:', res);
	}).catch(err => {
		console.error('用户信息更新失败:', err);
	});
};

// 计算是否显示主要内容（当没有弹窗打开时）
const isShowElement = computed(() => {
	return !Object.values(modalStates.value).some(state => state);
});

// 处理开始答题弹窗点击
const questionType = ref('');
const handleStartQues = (type) => {
	questionType.value = type;
	// 重置分数，避免累加
	completeScore.value = 0;
	openModal('question');
	// 传递问题类型到问题弹窗
}
// 处理问题弹窗完成
const completeScore = ref(0);
const handleComplete = (selectedAnswer) => {
	// 打开完成弹窗
	let score = selectedAnswer.filter(v => v.isCorrect).reduce((acc, cur) => acc + cur.score, 0);
	completeScore.value = score;
	openModal('complete');
	api.question.submitScore({
		id: localStorage.getItem('userId'),
		location: score,
	})
};

// 处理退出登录
const handleLogout = () => {
	closeAllModals();
	// 退出登录后，清除用户昵称和头像
	userNickname.value = '';
	userAvatar.value = '';
};
// 处理完成弹窗关闭
const handleCompleteModal = () => {
	// 退出登录
	closeModal('complete');
	// 重置分数
	completeScore.value = 0;
	localStorage.clear()
	userNickname.value = '';
	userAvatar.value = '';
	testApiCalls();
};

onMounted(() => {
	checkUserNickname();
	testApiCalls();
});
</script>

<template>
	<div class="home-container w-full h-full position-relative">
		<transition name="content-fade">
			<div v-show="isShowElement" class="main-content w-full h-full flex flex-col items-center">
				<div class="top-bg">
					<img src="../assets/images/1/top.png" alt="logo" class="w-[60%]" />
				</div>

				<div class="left-tools flex flex-col items-center w-[228px] gap-3">
					<img v-if="!userNickname" src="../assets/images/1/s-1.png" alt="开始答题" />
					<div class="login-success" v-else>
						<img src="../assets/images/1/s-4.png" alt="" class="bg-avatar">
						<img :src="avatarMap[userAvatar]" alt="" class="avatar-img">
					</div>
					<img src="../assets/images/1/s-2.png" alt="排行" @click="openModal('ranking')" />
					<img src="../assets/images/1/s-3.png" alt="设置" @click="openModal('setting')"
						class="cursor-pointer" />
				</div>

				<div class="start-btn" @click="handleStartClick"></div>
			</div>
		</transition>

		<!-- 开始答题弹窗 -->
		<StartQuestion :isVisible="modalStates.startQuestion" @close="() => closeModal('startQuestion')"
			@click="handleStartQues" />

		<!-- 登录弹窗 -->
		<LoginModal :isVisible="modalStates.login" @close="() => closeModal('login')" @login="handleLogin" />

		<!-- 设置弹窗 -->
		<SettingModal :isVisible="modalStates.setting" @close="() => closeModal('setting')" @save="handleSaveSettings"
			@logout="handleLogout" />

		<!-- 完成弹窗 -->
		<CompleteModal :isVisible="modalStates.complete" @close="() => closeModal('complete')"
			@complete="handleCompleteModal" :completeScore="completeScore" />

		<!-- 排行弹窗 -->
		<RankingModal :isVisible="modalStates.ranking" @close="() => closeModal('ranking')" />

		<!-- 问题弹窗 -->
		<QuestionModal :isVisible="modalStates.question" @close="() => closeModal('question')"
			@complete="handleComplete" :types="questionType" />
	</div>
</template>

<style lang="scss" scoped>
.home-container {
	background: url("../assets/images/1/bg.png") no-repeat center center fixed;
	background-size: cover;

	.main-content {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.left-tools {
		position: absolute;
		top: 20px;
		left: 20px;
		cursor: pointer;

		&>img {
			transition: all 0.3s ease;
			transform-origin: center;

			&:hover {
				transform: scale(1.03) translateY(-1px);
				filter: brightness(1.03);
			}
		}

		.login-success {
			width: 100%;
			height: 228px;
			background: rgba($color: #ffffff, $alpha: 0.8);
			border-radius: 54px;
			position: relative;
			transition: all 0.3s ease;
			transform-origin: center;
			display: flex;
			justify-content: center;
			align-items: center;
			box-sizing: border-box;

			.avatar-img {
				position: absolute;
				top: 54px;
				right: 54px;
				width: 120px;
				height: 120px;
				border-radius: 50%;
				z-index: 1;
			}

			.bg-avatar {
				width: 228px;
				height: 228px;
				position: relative;
				top: 4px;
			}

			&:hover {
				transform: scale(1.03) translateY(-1px);
				filter: brightness(1.03);
			}
		}
	}

	.start-btn {
		width: 50%;
		height: 10%;
		position: absolute;
		bottom: 10%;
		background: url("../assets/images/1/start.png") no-repeat center center;
		background-size: contain;
		cursor: pointer;
		border: none;

		&:active,
		&:hover {
			background: url("../assets/images/1/start_active.png") no-repeat center center;
			background-size: contain;
		}
	}
}

// 内容区域显示隐藏动画
.content-fade-enter-active,
.content-fade-leave-active {
	transition: all 0.4s ease;
}

.content-fade-enter-from,
.content-fade-leave-to {
	opacity: 0;
}

.content-fade-enter-to,
.content-fade-leave-from {
	opacity: 1;
}
</style>